import {getRequest} from "@/utils/api";


// 封装菜单请求工具
export const initMenu = (router, store) => {
    // 判断是否已经初始化过菜单
    if (store.state.routes.length > 0) {
        return;
    }
    getRequest("/system/config/menu").then(data => {
        // 判断数据是否存在
        if (data) {
            // 格式化Router
            let fmtRoutes = formatRoutes(data);
            // 添加到router
            router.addRoutes(fmtRoutes);
            // 将数据存入vuex
            store.commit('initRoutes', fmtRoutes);
        }
    })
}

export const formatRoutes = (routers) => {
    let fmtRoutes = [];
    routers.forEach(router => {
        let {
            path,
            component,
            name,
            iconcls,
            children,
        } = router;
        // children存在并且为一个数组
        if (children && children instanceof Array) {
            // 递归
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            iconCls: iconcls,
            children: children,
            component(resolve) {
                // 判断包名是什么开头
                if (component.startsWith("Home")) {
                    require(['../views/' + component + '.vue'], resolve);
                } else if (component.startsWith("Emp")) {
                    require(['../views/emp/' + component + '.vue'], resolve);
                } else if (component.startsWith("Per")) {
                    require(['../views/per/' + component + '.vue'], resolve);
                } else if (component.startsWith("Sal")) {
                    require(['../views/sal/' + component + '.vue'], resolve);
                } else if (component.startsWith("Sta")) {
                    require(['../views/sta/' + component + '.vue'], resolve);
                } else if (component.startsWith("Sys")) {
                    require(['../views/sys/' + component + '.vue'], resolve);
                }
            }
        }
        fmtRoutes.push(fmRouter)
    });
    return fmtRoutes;
}